package info.xingxingdd.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import info.xingxingdd.admin.entity.FileInfo;
import info.xingxingdd.admin.mapper.FileInfoMapper;
import info.xingxingdd.admin.service.FileInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件信息服务实现类
 */
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements FileInfoService {

    @Value("${file.upload.path:E:/project/file}")
    private String uploadPath;

    @Override
    public FileInfo uploadFile(MultipartFile file, String remark) throws IOException {
        // 获取文件信息
        String originalFilename = file.getOriginalFilename();
        long fileSize = file.getSize();
        
        // 生成文件标识
        String fileKey = UUID.randomUUID().toString().replace("-", "");
        
        // 计算MD5
        String md5 = DigestUtils.md5DigestAsHex(file.getInputStream());
        
        // 创建目录（按年月日分类）
        String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String dirPath = uploadPath + "/" + datePath;
        Path directory = Paths.get(dirPath);
        if (!Files.exists(directory)) {
            Files.createDirectories(directory);
        }
        
        // 保存文件
        String filePath = dirPath + "/" + fileKey + "_" + originalFilename;
        File destFile = new File(filePath);
        file.transferTo(destFile);
        
        // 保存文件信息到数据库
        FileInfo fileInfo = new FileInfo();
        fileInfo.setFileKey(fileKey);
        fileInfo.setFileName(originalFilename);
        fileInfo.setFilePath(filePath);
        fileInfo.setFileSize(fileSize);
        fileInfo.setMd5(md5);
        fileInfo.setStatus("active");
        fileInfo.setRemark(remark);
        
        LocalDateTime now = LocalDateTime.now();
        fileInfo.setCreateAt(now);
        fileInfo.setUpdateAt(now);
        
        this.save(fileInfo);
        
        return fileInfo;
    }

    @Override
    public boolean deleteFile(Integer id) {
        FileInfo fileInfo = this.getById(id);
        if (fileInfo != null) {
            // 删除物理文件
            File file = new File(fileInfo.getFilePath());
            if (file.exists()) {
                file.delete();
            }
            
            // 删除数据库记录
            return this.removeById(id);
        }
        return false;
    }
} 